<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="诉求类型" prop="demandsType">
        <el-select v-model="queryParams.demandsType" placeholder="请选择诉求类型" clearable style="width: 240px">
          <el-option label="问题咨询" value="问题咨询" />
          <el-option label="困难求助" value="困难求助" />
          <el-option label="投诉举报" value="投诉举报" />
          <el-option label="服务评价" value="服务评价" />
        </el-select>
      </el-form-item>
      <el-form-item label="诉求状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择诉求状态" clearable style="width: 240px">
          <el-option label="审核不通过" :value="-1" />
          <el-option label="待审核" :value="0" />
          <el-option label="待处理" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="营商中心状态" prop="ysStatus" v-if="isYingShangCenter">
        <el-select v-model="queryParams.ysStatus" placeholder="请选择营商中心状态" clearable style="width: 240px"> 
          <el-option label="受理中" :value="1" />
          <el-option label="已驳回" :value="2" />
          <el-option label="已同意" :value="3" /> 
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['claim:answerList:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['claim:answerList:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['claim:answerList:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['claim:answerList:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="answerList">
      <el-table-column type="index" label="序号" width="60" align="center" />

      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <!-- <el-table-column label="ID" align="center" key="demandsId" prop="demandsId" width="80" /> -->
 
      <el-table-column label="标题" align="center" key="demandsTitle" prop="demandsTitle" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="内容" align="center" key="demandsContent" prop="demandsContent" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="图片" align="center" key="images" width="120">
        <template slot-scope="scope">
          <div v-if="getImageList(scope.row.images).length > 0" style="display: inline-block; position: relative;">
            <el-image 
              :src="getImageList(scope.row.images)[0]" 
              :preview-src-list="getImageList(scope.row.images)" 
              style="width: 50px; height: 50px;" 
              fit="cover">
            </el-image>
            <span v-if="getImageList(scope.row.images).length > 1" style="position: absolute; bottom: -2px; right: -2px; background: rgba(0,0,0,0.6); color: white; font-size: 10px; padding: 1px 4px; border-radius: 2px;">
              {{ getImageList(scope.row.images).length }}
            </span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" align="center" key="companyName" prop="companyName" :show-overflow-tooltip="true" min-width="200" />
      <!-- <el-table-column label="企业联系人" align="center" key="contact" prop="contact" width="120" />
      <el-table-column label="企业联系电话" align="center" key="contactPhone" prop="contactPhone" width="120" />  -->
      <el-table-column label="联企人员" align="center" key="memberName" prop="memberName" width="120" />
      <!-- <el-table-column label="诉求状态" align="center" key="status" width="120">
        <template slot-scope="scope">
          <el-tag :type="getAppealStatusType(scope.row.status)">
            {{ getAppealStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="诉求状态" align="center" key="currentStatus" prop="currentStatus" width="120"/> 
      <el-table-column label="营商中心状态" align="center" key="ysStatus" width="120">
        <template slot-scope="scope">
          <el-tag :type="getYsStatusType(scope.row.ysStatus)">
            {{ getYsStatusText(scope.row.ysStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <!-- <el-table-column label="转入部门" v-if="columns[7].visible" align="center" key="upBranchName" prop="upBranchName" width="120" />
      <el-table-column label="转出部门" v-if="columns[8].visible" align="center" key="toBranchName" prop="toBranchName" width="120" /> -->
      <el-table-column label="答复内容" align="center" key="acceptContent" prop="acceptContent" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="创建时间" align="center" key="createTime" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleProcess(scope.row)">处置</el-button>
          <!-- v-hasPermi="['claim:answerList:process']" -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size" @pagination="getList" />

    <!-- 添加或修改诉求处置配置对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入企业名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入企业联系人" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入企业联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业诉求" prop="companyAppeal">
              <el-input v-model="form.companyAppeal" placeholder="请输入企业诉求" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="诉求内容" prop="appealContent">
              <el-input v-model="form.appealContent" type="textarea" placeholder="请输入诉求内容" :rows="4" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="转入部门" prop="transferInDept">
              <el-input v-model="form.transferInDept" placeholder="请输入转入部门" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转出部门" prop="transferOutDept">
              <el-input v-model="form.transferOutDept" placeholder="请输入转出部门" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联企人员" prop="liaisonPerson">
              <el-input v-model="form.liaisonPerson" placeholder="请输入联企人员" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处置状态" prop="handlingStatus">
              <el-select v-model="form.handlingStatus" placeholder="请选择处置状态">
                <el-option label="未受理" value="not_accepted" />
                <el-option label="处理中" value="processing" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="答复内容" prop="replyContent">
              <el-input v-model="form.replyContent" type="textarea" placeholder="请输入答复内容" :rows="4" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="诉求图片">
              <image-upload v-model="form.appealImage" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <!-- 处置对话框 -->
    <el-dialog title="诉求处置" :visible.sync="processOpen" width="1200px" append-to-body>
      <div style="display: flex; gap: 20px;">
        <!-- 左侧：诉求信息 -->
        <div style="flex: 1; padding-right: 20px;">
          <div style="font-weight: bold; margin-bottom: 16px; color: #303133;">诉求信息</div>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="企业名称">{{ processForm.companyName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="企业联系人">{{ processForm.contact || '-' }}</el-descriptions-item>
            <el-descriptions-item label="企业联系电话">{{ processForm.contactPhone || '-' }}</el-descriptions-item>
            <!-- <el-descriptions-item label="企业诉求">{{ processForm.demandsType || '-' }}</el-descriptions-item> -->
            <el-descriptions-item label="诉求标题">{{ processForm.demandsTitle || '-' }}</el-descriptions-item>
            <el-descriptions-item label="诉求内容">{{ processForm.demandsContent || '-' }}</el-descriptions-item>
            <el-descriptions-item label="诉求图片" v-if="getImageList(processForm.images).length > 0">
              <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <el-image 
                  v-for="(img, index) in getImageList(processForm.images)" 
                  :key="index"
                  :src="img" 
                  :preview-src-list="getImageList(processForm.images)" 
                  style="width: 120px; height: 120px; cursor: pointer;" 
                  fit="cover">
                </el-image>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="诉求状态">
              <span v-html="formatStatusWithRedBrackets(processForm.currentstatus)"></span>
            </el-descriptions-item>

            <el-descriptions-item label="联企人员审核备注">
              <div style="max-height: 100px; overflow-y: auto;">
                {{ processForm.remark || '-' }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 答复列表表格 -->
          <div style="margin-top: 20px;">
            <div style="font-size: 14px; font-weight: bold; margin-bottom: 12px; color: #303133;">答复列表</div>
            <el-table :data="replyList" border size="small" style="width: 100%;">
              <el-table-column prop="handler" label="经办人" align="center">
                <template slot-scope="scope">
                  {{ scope.row.chargeName || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="handlerPhone" label="经办人电话" align="center">
                <template slot-scope="scope">
                  {{ scope.row.chargePhone || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="chargeTime" label="预处理时间" align="center">
                <template slot-scope="scope">
                  {{ formatDateOnly(scope.row.chargeTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="处置状态" align="center">
                <template slot-scope="scope">
                  {{ getDisposalStatusText(scope.row.status) }}
                </template>
              </el-table-column>
              <el-table-column prop="acceptContent" label="答复结果" align="center" >
                <template slot-scope="scope">
                  <el-popover
                    placement="top-start"
                    title="答复结果"
                    width="300"
                    trigger="hover"
                    :content="scope.row.acceptContent || '-'">
                    <div 
                      slot="reference"
                      class="text-ellipsis-3" 
                      style="text-align: left; padding: 0 8px; cursor: pointer;"
                    >
                      {{ scope.row.acceptContent || '-' }}
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
              <template slot="empty">
                <span style="color: #909399;">暂无数据</span>
              </template>
            </el-table>
          </div>
        </div>

        <!-- 右侧：处置表单 -->
        <div style="flex: 1; padding-left: 20px; border-left: 1px solid #e4e7ed;" v-if="!isYingShangCenter || (isYingShangCenter && processForm.ysStatus === 1)">
          <el-form ref="processForm" :model="processForm" :rules="processRules" label-width="100px">
            <el-form-item label="经办人" prop="chargeName">
              <div style="display: flex; align-items: center; gap: 8px;">
                <!-- <span>{{ processForm.chargeName || '管理' }}</span> -->
                <el-input v-model="processForm.chargeName" placeholder="请输入经办人" maxlength="20" /> 
                <el-tag size="small" type="info">默认当前用户</el-tag>
              </div>
            </el-form-item>
            <el-form-item label="经办人电话" prop="chargePhone">
              <el-input v-model="processForm.chargePhone" placeholder="请输入经办人电话" maxlength="20" />
            </el-form-item>

            <!-- 营商中心最后处置的结果；不再展示转入部门、答复内容的选项 -->
            <el-form-item label="处置结果" prop="result" required v-if="isYingShangCenter">
              <el-radio-group v-model="processForm.result">
                <el-radio :label="1">同意</el-radio>
                <el-radio :label="2">不同意</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="转入部门" prop="moreBranchIds" v-if="isYingShangCenter && processForm.result === 1">
              
              <!-- 多选框 -->
              <el-select
                v-model="processForm.moreBranchIds"
                placeholder="请选择转入部门，可追加多个部门"
                filterable
                clearable 
                multiple
                :loading="branchLoading"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in filteredBranchOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="预处理时间" prop="chargeTime" v-if="!isYingShangCenter">
              <el-date-picker
                v-model="processForm.chargeTime"
                type="date"
                placeholder="请选择预处理时间"
                style="width: 100%;"
                value-format="yyyy-MM-dd"
              />
            </el-form-item> 
            <el-form-item label="处置状态" prop="status" required v-if="!isYingShangCenter">
              <el-radio-group v-model="processForm.status">
                <el-radio :label="1">受理/处置</el-radio>
                <el-radio :label="2">驳回/转部门</el-radio>
                <el-radio :label="3">呈报领导</el-radio><!--初始状态，不能呈报领导-->
                <el-radio :label="4">完成</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 非营商中心角色显示转入部门和答复内容 -->
            <el-form-item label="转入部门" prop="toBranchId" v-if="!isYingShangCenter && processForm.status === 2">
              <el-select
                v-model="processForm.toBranchId"
                placeholder="请选择转入部门"
                filterable
                clearable
                :loading="branchLoading"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in filteredBranchOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="!isYingShangCenter && processForm.status === 2">
              <div style="color: #909399; font-size: 12px; line-height: 1.5;">
                此处部门为可选项，如不选择转入部门则默认执行驳回操作
              </div>
            </el-form-item>

            <el-form-item label="答复内容" prop="acceptContent" required >
              <el-input 
                v-model="processForm.acceptContent" 
                type="textarea" 
                placeholder="请输入答复内容" 
                :rows="6" 
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item v-if="!isYingShangCenter">
              <div style="color: #909399; font-size: 12px; line-height: 1.5;">
                如不填写经办人则默认为平台预留的部门联系人或综合专干
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitProcessForm" v-if="!isYingShangCenter || (isYingShangCenter && processForm.ysStatus === 1)">提 交</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="诉求详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <!-- <el-descriptions-item label="诉求ID">{{ detailForm.demandsId }}</el-descriptions-item>
        <el-descriptions-item label="受理ID">{{ detailForm.acceptId }}</el-descriptions-item> -->
        <el-descriptions-item label="诉求标题">{{ detailForm.demandsTitle }}</el-descriptions-item>
        <el-descriptions-item label="诉求类型">{{ detailForm.demandsType }}</el-descriptions-item>
        <el-descriptions-item label="企业名称" :span="2">{{ detailForm.companyName }}</el-descriptions-item>
        <el-descriptions-item label="企业联系人">{{ detailForm.contact }}</el-descriptions-item>
        <el-descriptions-item label="企业联系电话">{{ detailForm.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="诉求内容" :span="2">{{ detailForm.demandsContent }}</el-descriptions-item>
        <el-descriptions-item label="诉求图片" :span="2" v-if="getImageList(detailForm.images).length > 0">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <el-image 
              v-for="(img, index) in getImageList(detailForm.images)" 
              :key="index"
              :src="img" 
              :preview-src-list="getImageList(detailForm.images)" 
              style="width: 120px; height: 120px; cursor: pointer;" 
              fit="cover">
            </el-image>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="联企人员">{{ detailForm.memberName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="诉求状态">
          <el-tag :type="getAppealStatusType(detailForm.status)">
            {{ getAppealStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="受理部门">{{ detailForm.branchName || '-' }}</el-descriptions-item>
        <!-- <el-descriptions-item label="转入部门">{{ detailForm.upBranchName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="转出部门">{{ detailForm.toBranchName || '-' }}</el-descriptions-item> -->
        <!-- <el-descriptions-item label="受理内容" :span="2">{{ detailForm.acceptContent || '-' }}</el-descriptions-item> -->
        <el-descriptions-item label="答复内容" :span="2">{{ detailForm.acceptContent || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ (detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2" v-if="detailForm.remark">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listAnswer, getAnswer, delAnswer, addAnswer, updateAnswer, processAnswer } from "@/api/claim/answerList"
import { listDemandsDepart, listBranch, replyDemandsBack, listDemandsDepartReply, ysCheckDemandDepart } from "@/api/biz/api"
import { mapGetters } from 'vuex'

const createProcessForm = () => ({
  acceptId: undefined,
  demandsId: undefined,
  companyName: undefined,
  demandsTitle: undefined,
  demandsContent: undefined,
  contact: undefined,
  contactPhone: undefined,
  demandsType: undefined,
  checkRemark: undefined,
  chargeName: '',
  chargePhone: '',
  chargeTime: '',
  status: undefined,
  acceptContent: '',
  toBranchId: undefined,
  moreBranchIds: [],
  ysStatus: undefined,
  // leaderIds: []
})

export default {
  name: "AnswerList",
  computed: {
    ...mapGetters(['user', 'phonenumber', 'name', 'deptId', 'roles']),
    currentUserName() {
      return this.user?.userName || this.name || ''
    },
    currentUserPhone() {
      return this.user?.phonenumber || this.phonenumber || ''
    },
    // 获取当前用户的部门ID（优先从 store 获取，如果没有则从 user 对象获取）
    currentDeptId() {
      if (this.deptId) {
        return this.deptId
      }
      // 兼容处理：从 user 对象中获取部门ID
      return this.user?.dept?.deptId || this.user?.deptId || null
    },
    // 过滤后的部门选项（排除当前用户的部门）
    filteredBranchOptions() {
      if (!this.currentDeptId) {
        // 如果没有部门信息，返回全部选项
        return this.branchOptions
      }
      // 过滤掉当前用户的部门
      return this.branchOptions.filter(item => item.deptId !== this.currentDeptId)
    },
    // 判断当前用户是否是营商中心角色
    isYingShangCenter() {
      // 从 user.roles 数组中查找角色名称或角色键为"营商中心"的角色
      const userRoles = this.user?.roles || []
      console.log('userRoles :',userRoles);
      
      if (userRoles.length > 0) {
        return userRoles.some(role => {
          return role.roleName === '营商中心'
        })
      } 
      return false
    },
    // 动态表单验证规则（根据角色调整）
    processRules() {
      const baseRules = {
        chargeName: [
          { required: true, message: "请输入经办人", trigger: "blur" }
        ],
        chargePhone: [
          { required: true, message: "请输入经办人电话", trigger: "blur" },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        chargeTime: [
          { required: true, message: "请选择预计处理时间", trigger: "change" }
        ],
        status: [
          { required: true, message: "请选择处置状态", trigger: "change" }
        ]
      }
      
      // 如果是营商中心角色，添加处置结果验证，不添加答复内容验证
      if (this.isYingShangCenter) {
        baseRules.result = [
          { required: true, message: "请选择处置结果", trigger: "change" }
        ]
      } else {
        // 非营商中心角色，添加答复内容验证
        // 注意：转入部门在"驳回/转部门"状态下为非必填，所以不添加验证规则
        baseRules.acceptContent = [
          { required: true, message: "请输入答复内容", trigger: "blur" }
        ]
      }
      
      return baseRules
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 诉求处置表格数据
      answerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示处置弹出层
      processOpen: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 部门下拉
      branchOptions: [],
      branchLoading: false,
      // 表单参数
      form: {},
      // 处置表单参数
      processForm: createProcessForm(),
      // 详情表单参数
      detailForm: {},
      // 答复列表数据
      replyList: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        demandsType: null,
        status: null,
        ysStatus: null
      },
      // 列信息
      // columns: [
      //   { key: 0, label: `ID`, visible: true },
      //   { key: 1, label: `企业名称`, visible: true },
      //   { key: 2, label: `企业联系人`, visible: true },
      //   { key: 3, label: `企业联系电话`, visible: true },
      //   { key: 4, label: `企业诉求`, visible: true },
      //   { key: 5, label: `诉求内容`, visible: true },
      //   { key: 6, label: `诉求图片`, visible: true },
      //   { key: 7, label: `转入部门`, visible: false },
      //   { key: 8, label: `转出部门`, visible: false },
      //   { key: 9, label: `联企人员`, visible: true },
      //   { key: 10, label: `处置状态`, visible: true },
      //   { key: 11, label: `答复内容`, visible: true },
      //   { key: 12, label: `创建时间`, visible: true }
      // ],
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        contactPerson: [
          { required: true, message: "企业联系人不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "企业联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        companyAppeal: [
          { required: true, message: "企业诉求不能为空", trigger: "blur" }
        ],
        appealContent: [
          { required: true, message: "诉求内容不能为空", trigger: "blur" }
        ]
      },
    }
  },
  created() {
    this.getList()
    this.fetchBranchOptions()
  },
  watch: {
    'processForm.status'(val) {
      if (val !== 2) {
        this.processForm.toBranchId = undefined
      }
    }
  },
  methods: {
    /** 查询诉求处置列表 */
    getList() {
      this.loading = true
      // 构建符合 API 要求的查询参数
      const params = {
        current: (this.queryParams.current && this.queryParams.current > 0) ? this.queryParams.current - 1 : 0, // API 使用从 0 开始的索引
        size: this.queryParams.size || 10
      }
 
      if (this.queryParams.demandsType !== null) {
        params.demandsType = this.queryParams.demandsType
      }
      
      // 只有当 status 有值时才添加
      if (this.queryParams.status !== null) {
        params.status = this.queryParams.status
      }
      
      
      if (this.isYingShangCenter && this.queryParams.ysStatus !== null) {
        params.ysStatus = this.queryParams.ysStatus
      }

      listDemandsDepart(params).then(response => {
        console.log('诉求部门列表 ：',response);
        
        this.answerList = response.data?.records || []
        this.total = response.data?.total || 0
        this.loading = false
      })
    },
    // 获取部门下拉
    fetchBranchOptions() {
      this.branchLoading = true
      listBranch()
        .then(response => {
          this.branchOptions = response.data || []
        })
        .catch(error => {
          console.error('获取部门列表失败', error)
        })
        .finally(() => {
          this.branchLoading = false
        })
    },
    // 取消按钮
    // cancel() {
    //   this.open = false
    //   this.reset()
    // },
    // 表单重置
    // reset() {
    //   this.form = {
    //     id: undefined,
    //     companyName: undefined,
    //     contactPerson: undefined,
    //     contactPhone: undefined,
    //     companyAppeal: undefined,
    //     appealContent: undefined,
    //     appealImage: undefined,
    //     transferInDept: undefined,
    //     transferOutDept: undefined,
    //     liaisonPerson: undefined,
    //     handlingStatus: "not_accepted",
    //     replyContent: undefined,
    //     remark: undefined
    //   }
    //   this.resetForm("form")
    // },
    // 处置表单重置
    resetProcessForm() {
      this.processForm = createProcessForm()
      this.replyList = []
      this.$nextTick(() => {
        if (this.$refs["processForm"]) {
          this.$refs["processForm"].clearValidate()
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    }, 
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset()
    //   this.open = true
    //   this.title = "添加诉求处置"
    // },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset()
    //   const id = row.id || this.ids
    //   getAnswer(id).then(response => {
    //     this.form = response.data
    //     this.open = true
    //     this.title = "修改诉求处置"
    //   })
    // },
    /** 处置按钮操作 */
    handleProcess(row) {
      console.log('row :',row);
      this.resetProcessForm()
      const baseForm = createProcessForm()
      this.processForm = Object.assign(baseForm, {
        acceptId: row.acceptId,
        demandsId: row.demandsId,
        companyName: row.companyName,
        demandsTitle: row.demandsTitle,
        demandsContent: row.demandsContent || '-',
        currentstatus: '',
        contact: row.contact,
        contactPhone: row.contactPhone,
        demandsType: row.demandsType,
        checkRemark: row.checkRemark,
        images: row.images,
        remark: row.remark,
        chargeName: this.currentUserName || '', //row.handlerName || row.chargeName || 
        chargePhone: this.currentUserPhone || '', //row.handlerPhone || row.chargePhone || 
        chargeTime: null, //row.chargeTime || 
        acceptContent: null, //row.acceptContent || 
        toBranchId: null, //row.toBranchId || undefined,
        status: 1, // 默认值
        ysStatus: row.ysStatus // 保存营商中心状态
      })
      // 答复列表数据
      if (row.acceptId) {
        listDemandsDepartReply(row.acceptId).then(response => {
          this.replyList = response.data.demandsReplyList || []
          // 从接口返回的数据中获取 currentStatus 并设置到 processForm
          if (response.data && response.data.demandsDepart && response.data.demandsDepart.currentStatus) {
            this.processForm.currentstatus = response.data.demandsDepart.currentStatus
          }
          // 从接口返回的数据中获取 toBranchId 并设置到 moreBranchIds（默认带入已选择的部门）
          if (response.data && response.data.demandsDepart && response.data.demandsDepart.toBranchId) {
            const toBranchId = response.data.demandsDepart.toBranchId
            // 如果是数组，直接使用；如果是单个值，转换为数组
            this.processForm.moreBranchIds = Array.isArray(toBranchId) ? [...toBranchId] : [toBranchId]
          }
        }).catch(error => {
          console.error('获取答复列表失败', error)
          this.replyList = []
        })
      }
      this.processOpen = true
    },
    /** 查看详情操作 */
    handleView(row) {
      this.detailForm = { ...row }
      this.detailOpen = true
    },
    /** 提交按钮 新增或编辑的诉求*/
    // submitForm: function() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != undefined) {
    //         updateAnswer(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       } else {
    //         addAnswer(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       }
    //     }
    //   })
    // },
    /** 提交处置表单 */
    submitProcessForm: function() {
      this.$refs["processForm"].validate(valid => {

        // 这里要区分，营商中心和非营商中心的情况，分别调用不同的接口
        if (this.isYingShangCenter) {
          // 营商中心情况
          if (valid) {
            const payload = {
              acceptId: this.processForm.acceptId,
              acceptContent: this.processForm.acceptContent, 
              chargeName: this.processForm.chargeName,
              chargePhone: this.processForm.chargePhone, 
              status: this.isYingShangCenter ? this.processForm.result : this.processForm.status, 
              moreBranchIds: (this.isYingShangCenter && this.processForm.result === 1) ? (this.processForm.moreBranchIds || []) : [],
            }
            ysCheckDemandDepart(payload).then(response => {
              this.$modal.msgSuccess("营商中心介入审核成功")
              this.processOpen = false
              this.getList()
            })
          }

        } else {
          // 非营商中心情况

          if (valid) {
            const payload = {
              acceptId: this.processForm.acceptId,
              demandsId: this.processForm.demandsId,
              chargeName: this.processForm.chargeName,
              chargePhone: this.processForm.chargePhone,
              chargeTime: this.processForm.chargeTime,
              acceptContent: this.processForm.acceptContent,
              status: this.processForm.status, 
              toBranchId: this.processForm.status === 2 ? this.processForm.toBranchId : 0,
              // leaderIds: this.processForm.status === 3 ? (this.processForm.leaderIds || []) : [],
            }
            replyDemandsBack(payload).then(response => {
              this.$modal.msgSuccess("处置成功")
              this.processOpen = false
              this.getList()
            })
          }

        }
      
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除诉求处置编号为"' + ids + '"的数据项？').then(function() {
        return delAnswer(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('claim/answerList/export', {
        ...this.queryParams
      }, `answerList_${new Date().getTime()}.xlsx`)
    },
 
    // 获取诉求状态文本（根据数字状态）
    getAppealStatusText(status) {
      // 处理数字状态值：-1, 0, 1, 2
      const statusMap = {
        '-1': '审核不通过',
        '0': '待审核',
        // '1': '待处理',
        '1': '处置中',
        '2': '已完成'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return statusMap[statusKey] || (status !== null && status !== undefined ? String(status) : '-')
    },
   // 获取诉求状态类型（根据数字状态）
   getAppealStatusType(status) {
      // 处理数字状态值：-1, 0, 1, 2
      const typeMap = {
        '-1': 'danger',
        '0': 'warning',
        '1': 'primary',
        '2': 'success'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return typeMap[statusKey] || ''
    },
    
    getYsStatusText(status) {
      // const typeMap = {
      //   '1': 'primary',
      //   '2': 'danger',
      //   '3': 'success'
      // }
      // return typeMap[status] || ''

      const statusMap = {
        '1': '受理中',
        '2': '已驳回',
        '3': '已同意'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return statusMap[statusKey] || (status !== null && status !== undefined ? String(status) : '-')

    },
    getYsStatusType(status) { 
      const typeMap = {
        '-': 'warning',
        '1': 'primary',
        '2': 'danger',
        '3': 'success',
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : '-'
      return typeMap[statusKey] || ''
    },
    
 
    // 解析图片字符串为数组
    getImageList(images) {
      if (!images) {
        return []
      }
      // 如果已经是数组，直接返回并过滤空值
      if (Array.isArray(images)) {
        return images.filter(img => img && (typeof img === 'string' ? img.length > 0 : true))
      }
      // 如果是字符串，按逗号分割并过滤空值
      if (typeof images === 'string') {
        return images.split(',').map(img => img.trim()).filter(img => img.length > 0)
      }
      return []
    },
    // 格式化日期（只显示日期，不显示时分秒）
    formatDateOnly(dateTime) {
      if (!dateTime) {
        return '-'
      }
      // 处理 ISO 格式：2025-11-07T22:49:11.000+08:00
      if (typeof dateTime === 'string') {
        // 如果是 ISO 格式，提取日期部分
        if (dateTime.includes('T')) {
          return dateTime.split('T')[0]
        }
        // 如果已经是 yyyy-MM-dd 格式，直接返回
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateTime)) {
          return dateTime
        }
        // 如果是 yyyy-MM-dd HH:mm:ss 格式，提取日期部分
        if (/^\d{4}-\d{2}-\d{2}\s/.test(dateTime)) {
          return dateTime.split(' ')[0]
        }
      }
      return dateTime
    },
    // 获取处置状态文本（根据数字状态）
    getDisposalStatusText(status) {
      const statusMap = {
        '0': '未处置',
        '1': '受理/处置',
        '2': '驳回/转部门',
        '3': '呈报领导',
        '4': '完成'
      }
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return statusMap[statusKey] || (status !== null && status !== undefined ? String(status) : '-')
    },
    // 校验转部门必填
    validateBranchRequired(rule, value, callback) {
      if (this.processForm && this.processForm.status === 2 && !value) {
        callback(new Error("请选择转入部门"))
      } else {
        callback()
      }
    },
    // 格式化状态文本，将中文括号中的内容用红色显示
    formatStatusWithRedBrackets(status) {
      if (!status) {
        return '-'
      }
      // 使用正则表达式匹配中文括号（）中的内容
      // 匹配模式：中文左括号（ + 内容 + 中文右括号）
      const regex = /（([^）]+)）/g
      // 将括号中的内容替换为红色样式
      const formatted = String(status).replace(regex, '<span style="color: red;">（$1）</span>')
      return formatted
    }
  }
}
</script>

<style scoped>
.text-ellipsis-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  line-height: 1.5;
}
</style>
